<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="excel-data-load">
    <div class="steps">
      <el-steps :active="active" style="width: 100%" align-center>
        <el-step title="选择文件" />
        <el-step title="建立映射关系" />
        <el-step title="导入完成" />
      </el-steps>
    </div>
    <div class="upload_list" v-show="active === 1">
      <ChooseFile ref="chooseFileRef" @handleEvent="handleEvent" />
    </div>
    <div class="upload_list" v-if="active === 2">
      <Mapping :key="mappingFlag" :isBack="isBack" :mappingData="mappingData" :tableHeaderMap="tableHeaderMap" :sheetsDataMap="sheetsDataMap" :uploadFile="uploadFile" :formInfo="formInfo" :isSearchTableInfo="isSearchTableInfo" ref="mappingRef" />
    </div>
    <div class="finish" v-show="active === 3" v-loading="loading" element-loading-text="加载中...">
      <LoadFinish v-if="active === 3" :data="loadSuccessDataCount" />
    </div>
    <div class="option_btn">
      <el-button size="small" type="primary" v-show="active === 2" @click="step('pre')">上一步</el-button>
      <el-button size="small" type="primary" v-show="active === 1" @click="step('next')">下一步</el-button>
      <el-button size="small" type="primary" v-show="active === 2" @click="step('next')">确认导入</el-button>
      <el-button size="small" type="primary" v-show="active === 3" @click="finish">返回首页</el-button>
      <el-button size="small" v-show="active < 3" @click="cancel">返回</el-button>
    </div>
  </div>
</template>
<script  setup name="LoadExcel">
import axios from 'axios';
import { getToken } from '@/utils/auth';
import ChooseFile from './ChooseFile.vue';
import Mapping from './Mapping.vue';
import LoadFinish from './LoadFinish.vue';
import { getMetadataTableInfo, importExcelAboutData } from '@/api/metaData';
const emits = defineEmits(['handleEvent']);
const active = ref(1);
const mappingRef = ref(null);
const loading = ref(false);
// 上传文件相关信息
const formInfo = ref({});
const isSearchTableInfo = ref(false); // 是否重新选择业务场景或者要素库类型,更新表结构
const tableHeaderMap = ref(null);
const sheetsDataMap = ref(null);
const uploadFile = ref(null);
const uploadFileFlag = ref(false);
const mappingFlag = ref(false);
const chooseFileRef = ref(null);
// 映射数据
const mappingData = ref([]);
const isBack = ref(false); // 判断是否第三步返回
const tableList = ref([]); // 要素库表信息
const loadSuccessDataCount = ref(0); // 导入成功数
const handleEvent = (data) => {
  // if (data?.type === 'fileData') {
  //   const { tableHeaderMap, sheetsDataMap, uploadFile } = data?.data;
  //   tableHeaderMap.value = tableHeaderMap;
  //   sheetsDataMap.value = sheetsDataMap;
  //   uploadFile.value = uploadFile;
  //   mappingFlag.value=true;
  //   nextTick(() => {
  //     mappingFlag.value=false;
  //   })
  // }
};
const step = async (type) => {
  if (type === 'next') {
    if (active.value == 1) {
      // chooseFileRef.value.handleData();
      tableHeaderMap.value = chooseFileRef.value.titleMap;
      sheetsDataMap.value = chooseFileRef.value.sheetsDataMap;
      uploadFile.value = chooseFileRef.value.loadFile;
      formInfo.value = chooseFileRef.value.formInfo;
      isSearchTableInfo.value = chooseFileRef.value.isSceneOrDatabaseChange; 
      let flag1 = await chooseFileRef.value.form1Ref.validate((valid, fields) => {
        if (valid) {
          return true;
        } else {
          return false;
        }
      })
      let flag2 = await chooseFileRef.value.form2Ref.validate((valid, fields) => {
        if (valid) {
          return true;
        } else {
          return false;
        }
      })
      if (!flag1 || !flag1) {
        return;
      }
      if (!chooseFileRef.value.loadFile) {
        ElMessage({ showClose: true, message: '请先上传文件！', type: 'warning' });
        return;
      }
      isBack.value = false;
      active.value++; 
    } else if (active.value == 2) {
      mappingData.value = mappingRef.value.mappingList;
      let canNextFlag = mappingData.value.some(item => item.toFieldList.some(field => field.metadataField))
      if (!canNextFlag) {
        ElMessage({ showClose: true, message: '请先建立映射关系！', type: 'warning' });
        return;
      }
      submitAdd();
    }
    
  } else {
    if (active.value == 3) {
      isBack.value = true;
    } else if (active.value == 2) {
      // 切换上一步,重置是否改变业务场景和要素库类型标识为false
      chooseFileRef.value.isSceneOrDatabaseChange = false;
      mappingData.value = mappingRef.value.mappingList;
    }
    active.value--;
  }
};
// 数据导入
const submitAdd = () => {
  let mapFields = {}
  mappingData.value.forEach(item =>{
    mapFields[`${item.sheetName}::${item.tableName}`] = item.toFieldList;
  })
  const fm = new FormData();
  fm.append('file', uploadFile.value);
  fm.append('mapFields', JSON.stringify(mapFields));
  fm.append('dataQualityId', '111');
  fm.append('dataQuality', 'good');
  for (let key in formInfo.value) {
    fm.append(key, formInfo.value[key]);
  }
  // let VITE_APP_BASE_API = '/dev-api';
  // if (import.meta.env.MODE === 'production') {
  //   VITE_APP_BASE_API = '/prod-api';
  // }
  // if (import.meta.env.MODE === 'green') {
  //   VITE_APP_BASE_API = '/isfd-api';
  // }
  // axios
  //   .post(`${VITE_APP_BASE_API}/isfd/metadataManagement/save`, fm, {
  //     headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer ' + getToken() }
  //   })
  importExcelAboutData(fm).then((res) => {
    if (res.data.code == 200) {
      ElMessage({ showClose: true, message: res.data.msg, type: 'success' });
      loadSuccessDataCount.value = res.data.data;
      active.value++; 
    } else {
      ElMessage({ showClose: true, message: res.data.msg, type: 'error' });
    }
  });
};
// 完成组建
const finish = () => {
  emits('handleEvent', { component: 'Entry', type: 'finish' });
  // 跳转元数据管理
};
// 取消
const cancel = () => {
  emits('handleEvent', { component: 'Entry', type: 'cancel' });
};

onMounted(() => {
  
});
</script>
<style lang="scss" scoped>
.excel-data-load {
  padding: 10px;
  width: 100%;
  height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow: scroll;
  font-size: 12px;
  .steps {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top:30px;
  }
  .upload {
    width: 600px;
    margin-top: 20px;
    .upload_content {
      width: 600px;
      text-align: center;
      .upload_form {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }
    }
  }
  .upload_list,
  .upload_success {
    margin-top: 10px;
    overflow: scroll;
    // min-height: calc(100vh - 251px);
    width: 100%;
  }
  .option_btn {
    margin-top: 20px;
  }
  .upload_success {
    margin-top: 10px;
    .upload_success_message {
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }
  .finish {
    width: 600px;
    margin-top: 20px;
  }
  :deep(.el-step__title) {
    font-size: 12px;
  }
}
</style>
